﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace QD.Web.Upload
{
    public class UploadImageConfig : UploadFileConfig
    {
        [XmlAttribute(AttributeName = "MaxWidth")]
        public Int32 MaxWidth { get; set; }
        [XmlAttribute(AttributeName = "MaxHeigh")]
        public Int32 MaxHeight { get; set; }

        public override void SaveFile(HttpPostedFile file, string saveFileName)
        {
            Image image = Image.FromStream(file.InputStream);

            Int32 _w = 0, _h = 0;
            Double _r = 0;
            _r = image.Width / (Double)image.Height;

            _w = image.Width;
            _h = image.Height;

            if (MaxWidth > 0 && image.Width > MaxWidth)
            {
                _w = MaxWidth;
                _h = (Int32)(_w / _r);
            }
            if (MaxHeight > 0 && image.Height > MaxHeight)
            {
                _h = Math.Min(MaxHeight, _h);
                _w = (Int32)(_h * _r);
            }
            //cut image 
            Bitmap newImage = new Bitmap(_w, _h);
            Graphics g = Graphics.FromImage(newImage);
            g.Clear(System.Drawing.Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(image
              , new Rectangle(0, 0, _w, _h)
              , new Rectangle(0, 0, image.Width, image.Height)
              , GraphicsUnit.Pixel);
            g.Dispose();
            image.Dispose();

            String saveFullPath = Path.Combine(this.FullPath, saveFileName);
            try
            {
                newImage.Save(saveFullPath);
            }
            finally
            {
                newImage.Dispose();
            }
        }
    }
}
